package com.designschool.base.data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.designschool.base.util.ObjectUtils;
import com.designschool.base.util.StringUtils;
import com.designschool.base.util.ToastUtils;

import android.R.bool;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/****
 * 
 * @项目名:chake  
 * 
 * @类名:ChakesheData.java  
 * 
 * @创建人:chakeshe 
 *
 * @类描述:数据库以及表创建类
 * 
 * @date:2015-7-26
 * 
 * @Version:1.0 
 *
 *****************************************
 */
public class ChakesheData extends SQLiteOpenHelper {
    /***
     * 数据库版本，名称
     */
    private static int version = 1;
    private static String name = "chakeshe";

    /***
     * 创建表信息
     */
    private DatafieldBean datafield;

    private Context context;

    private String field = "";

    private SQLiteDatabase db;

    private boolean flag = false;

    /***
     * 增加，读取，查找，删除标志
     */
    private Map<String, Object> map;
    private List<Map<String, Object>> listMaps;

    public ChakesheData(Context context, DatafieldBean datafield) {
        super(context, name, null, version);
        this.datafield = datafield;
        this.context = context;
        Log.e("ChakesheData==>", datafield.table);
    }

    /***
     * 删除重新创建
     */
    public void onUpdate(){
        
    }
    
    /***
     * 删除表
     */
    public void OnDelete(){
        db=getWritableDatabase();
        db.execSQL("delete table "+datafield.table);
        db.close();
    }
    
    /***
     * 创建表
     */
    public void onSetup() {
        db = getWritableDatabase();
        if (datafield.listfield != null && datafield.listfield.size() > 0) {
            field = "create table  if not exists " + datafield.table
                    + "(_id integer PRIMARY KEY AUTOINCREMENT, ";
            for (int i = 0; i < datafield.listfield.size(); i++) {
                field += datafield.listfield.get(i) + " varchar(100) ,";
            }
            field = field.substring(0, field.length() - 1) + ")";
            Log.e("table==>", field);
            db.execSQL(field);
        } else {
            ToastUtils.show(context, "创建表" + datafield.table + "失败，请查看是否存在字段！");
        }
    }

    /***
     * 创建对应表
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.e("onCreate==>", datafield.table);
        if (datafield.listfield != null && datafield.listfield.size() > 0) {
            field = "create table  if not exists " + datafield.table
                    + " (_id integer PRIMARY KEY AUTOINCREMENT, ";
            for (int i = 0; i < datafield.listfield.size(); i++) {
                field += datafield.listfield.get(i) + " varchar(100) ,";
            }
            field = field.substring(0, field.length() - 1) + ")";
            Log.e("table==>", field);
            db.execSQL(field);
        } else {
            ToastUtils.show(context, "创建表" + datafield.table + "失败，请查看是否存在字段！");
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    /***
     * 增加一个数据到数据库
     * 
     * @param map
     */
    public void Add(Map<String, Object> map) {
        db = getWritableDatabase();
        ContentValues values = new ContentValues();
        for (int i = 0; i < datafield.listfield.size(); i++) {
            if(map.containsKey(datafield.listfield.get(i))&&
                    !ObjectUtils.isEquals(map.get(datafield.listfield.get(i)), null)){
            values.put(datafield.listfield.get(i),
                    map.get(datafield.listfield.get(i)).toString());
            }
        }
        db.insert(datafield.table, null, values);
        Log.e("add", "成功！");
        db.close(); 
    }

    /***
     * 批量增加数据到数据库
     * 
     * @param listMaps
     */
    public void AddAll(List<Map<String, Object>> listMaps) {
        db = getWritableDatabase();
        ContentValues values = new ContentValues();

        for (int j = 0; j < listMaps.size(); j++) {

            for (int i = 0; i < datafield.listfield.size(); i++) {
                if(listMaps.get(j).containsKey(datafield.listfield.get(i))&&
                        !ObjectUtils.isEquals(listMaps.get(j).get(datafield.listfield.get(i)), null)){
                values.put(datafield.listfield.get(i),
                        listMaps.get(j).get(datafield.listfield.get(i))
                                .toString());
                }
            }

            db.insert(datafield.table, null, values);
            Log.e("add", "成功！");
        }
        db.close();
    }

    /***
     * 读取全部
     * 
     * @return
     */
    public List<Map<String, Object>> ReadAll() {

        db = getReadableDatabase();
        listMaps = new ArrayList<Map<String, Object>>();
        Cursor cursor = db.rawQuery("select * from " + datafield.table, null);
        while (cursor.moveToNext()) {
            map = new HashMap<String, Object>();
            map.put("_id", cursor.getInt(0));
            for (int i = 0; i < datafield.listfield.size(); i++) {
                map.put(datafield.listfield.get(i), cursor.getString(i + 1));
            }
            listMaps.add(map);
        }
        db.close();
        return listMaps;
    }

    /***
     * 条件查找全部符合的数据
     * 
     * @param map
     *            数据
     * @param fieldo
     *            条件1
     * @param fieldw
     *            条件2
     * @param fields
     *            条件3
     * @param order_by 排序 true 倒序
     * @return
     */
    public List<Map<String, Object>> SearchAll(Map<String, Object> map,
            String fieldo, String fieldw, String fields,boolean order_by) {
        flag = false;
        db = getReadableDatabase();
        Cursor cursor;
        listMaps = new ArrayList<Map<String, Object>>();
        // field="select * from chakeshe where name=\'ceshi0\' and password=\'ceshi1\'";
        field = field = "select * from " + datafield.table;
        if (!StringUtils.isEmpty(fieldo)) {

            field += " where " + fieldo + "=\'" + map.get(fieldo) + "\'";
            flag = true;
        }

        if (!StringUtils.isEmpty(fieldw)) {
            if (flag) {
                field += " and " + fieldw + "=\'" + map.get(fieldw) + "\'";
            } else {
                field += " where " + fieldw + "=\'" + map.get(fieldw) + "\'";
            }
            flag = true;
        }

        if (!StringUtils.isEmpty(fields)) {
            if (flag) {
                field += " and " + fields + "=\'" + map.get(fields) + "\'";
            } else {
                field += " where " + fields + "=\'" + map.get(fields) + "\'";
            }
        }
        if(order_by){
        field+="order by _id desc";
        }
        Log.e("Field==>", field);
        cursor = db.rawQuery(field, null);
        while (cursor.moveToNext()) {
            map = new HashMap<String, Object>();
            map.put("_id", cursor.getInt(0));
            for (int i = 0; i < datafield.listfield.size(); i++) {
                map.put(datafield.listfield.get(i), cursor.getString(i + 1));
            }
            listMaps.add(map);
        }
        db.close();

        return listMaps;
    }

    /***
     * 删除数据
     * 
     * @param map
     * @param field
     * @return
     */
    public boolean Delete(Map<String, Object> map, String field) {
        flag = false;
        db = getWritableDatabase();
        flag = (db.delete(datafield.table, field + "=?", new String[] { map
                .get(field).toString() }) == 1) ? true : false;
        db.close();
        return flag;
    }
    
    /***
     * 删除数据
     * 
     * @param map
     * @param field
     * @return
     */
    public boolean Delete(Map<String, Object> map, String field,String sign) {
        flag = false;
        db = getWritableDatabase();
        flag = (db.delete(datafield.table, field +sign+ "?", new String[] { map
                .get(field).toString() }) == 1) ? true : false;
        db.close();
        return flag;
    }
    
    /***
     * 删除数据
     * 
     * @param map
     * @param field
     * @return
     */
    public boolean Delete(Map<String, Object> map, List<Map<String, Object>> termmaps) {
        flag = false;
        db = getWritableDatabase();
        String term = "";
        String[] terms =new String[termmaps.size()];
        for(int i=0;i<termmaps.size();i++){
            term+=(termmaps.get(i).get("field").toString()+termmaps.get(i).get("sign").toString()+" ");
            terms[i]=termmaps.get(i).get("field").toString();
        }
        
        Log.e("term==>", term);
        
        flag = (db.delete(datafield.table, term,  terms) == 1) ? true : false;
        db.close();
        return flag;
    }

    /***
     * 更新数据
     * @param map
     * @param field
     * @return
     */
    public boolean Update(Map<String, Object> map, String field) {
        db = getWritableDatabase();
        ContentValues values = new ContentValues();
//        String sql="update "+datafield.table+" set ";
        for (int i = 0; i < datafield.listfield.size(); i++) {
            if(map.containsKey(datafield.listfield.get(i))&&
                    !ObjectUtils.isEquals(map.get(datafield.listfield.get(i)), null)){
//                sql+=datafield.listfield.get(i)+"='"+map.get(datafield.listfield.get(i))+"' ,";
            values.put(datafield.listfield.get(i),
                    map.get(datafield.listfield.get(i)).toString());
            }
//            Log.e("Field==>", field);
        }
//        if(sql.lastIndexOf(",")>sql.length()-3){
//            sql=sql.substring(0,sql.lastIndexOf(",")-1)+" ";
//        }
        
//        sql+="where "+field+"="+map.get(field);
        
//        Log.e("sql==>", sql);
//        db.rawQuery(sql, null);
         
        flag = (db.update(datafield.table, values, field + "=?",
                new String[] { map.get(field).toString() }) >0) ? true : false; 
        db.close();
//        Log.e("flag==>", flag+"");
        return flag;
    }

}
